import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { base, ajax, toast, createPage } from 'nc-lightapp-front';
import { initTemplate, afterEvent, searchClick } from './events';
import { setForm } from 'ssccommon/utils/setComponentUsed';
import requestApi from './requestApi'
import './index.less';

window.pageCode = {
    searchPage: '201102621_2621_IWEB'
};
window.fyytAreaCode = {
    searchArea: 'search',
    billsArea: 'head',
    bodysArea: 'accrued_detail'
};

export default class Fyyt extends Component {
    constructor(props) {
        super(props);
        setForm(props, window.fyytAreaCode.searchArea)
        this.state = {
            showFyytModal: true,

        }
        let { form, button, table, editTable, search } = this.props;
        let { setSearchValue, setSearchValByField, getAllSearchData } = search;
        this.setSearchValByField = setSearchValByField;//设置查询区某个字段值
        this.getAllSearchData = getAllSearchData;//获取查询区所有字段数据
        this.isError = false; //转单编辑后字段是否通过验证

        if (this.props.showFyytModal) {
            initTemplate.call(this, props);
        }
    }
    setTransferBtnDisabled(flag) {
        //设置“冲借款”按钮是否可用
        let btnObj = document.querySelector('.area-right .main-button');
        if (flag == true) {
            btnObj&&btnObj.setAttribute('disabled', true);
        } else {
            btnObj&&btnObj.removeAttribute('disabled');
        }

    }

    componentDidMount() {
        //设置“冲借款”按钮在不勾选任何数据的时候也可用，添加监听 begin
        /* let that = this;
        var time = setInterval(() => {
            let btnObj = document.querySelector('.area-right .main-button');
            if (btnObj) {
                clearInterval(time);
                btnObj.addEventListener('click', function () {
                    //判断是否有已选的条目，有就直接return， 无则继续执行逻辑
                    let selectdata = that.props.transferTable.getTransferTableSelectedValue()
                    if (selectdata != undefined && selectdata.head != undefined && selectdata.head.length > 0) {
                        return;
                    }
                    window.pageFyytClick(null);
                })
            }
        }, 300) */
        //end
        this.props.transferTable.setTransferTableValue(window.fyytAreaCode.billsArea, window.fyytAreaCode.bodysArea, [], 'pk_accrued_bill', 'pk_accrued_detail');
    }

    render() {
        let { form, button, table, editTable, search, transferTable } = this.props;
        let { NCCreateSearch } = search;
        let { createButton } = button;
        let { createEditTable } = editTable;
        let { createTransferTable } = transferTable;
        let tradetype = this.props.getUrlParam("tradetype");
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        return (
            // "201102BCLF-0013": "预提单",
            <div className="nc-single-table" style = {{backgroundColor:'#e0e4ec'}}>

                {/*
                <div className="title">{multiLang && multiLang.get('201102BCLF-0013')}</div>
            <div className="header">

            </div>
            <div className="content-wrap">
                <div className="bar">

                </div>
            </div>
            */}

                <div className="nc-singleTable-search-area">
                    {NCCreateSearch(
                        window.fyytAreaCode.searchArea,//模块id
                        {
                            clickPlanEve: searchClick.bind(this),//点击高级面板中的查询方案事件
                            clickSearchBtn: searchClick.bind(this),//   点击按钮事件
                            defaultConditionsNum: 1, //默认显示几个查询条件
                            onAfterEvent: afterEvent()//编辑后事件
                        }
                    )}
                </div>
                <div className="nc-singleTable-table-area" >
                    {createTransferTable(
                        {
                            editStatus: true,
                            headTableId: window.fyytAreaCode.billsArea,//表格组件id
                            bodyTableId: window.fyytAreaCode.bodysArea,//子表模板id
                            fullTableId: window.fyytAreaCode.bodysArea,//主子拉平模板id
                            //点击加号展开，设置表格数据
                            // "201102BCLF-0003": "核销预提",
                            transferBtnText: multiLang && multiLang.get('201102BCLF-0003'), //转单按钮显示文字
                            containerSelector: '#fyyttransfer', //容器的选择器 必须唯一,用于设置底部已选区域宽度
                            cacheItem: ['verify_amount', "pk_accrued_bill", "pk_accrued_detail", "billno", "pk_iobsclass", "rest_amount"], //缓存字段
                            editableItem: ['verify_amount'], //可编辑字段
                            afterEvent: (attrcode, value, record, index, oldvalue) => {
                                console.log('编辑后事件', attrcode, value, record, index, oldvalue);

                                switch (attrcode) {
                                    case 'verify_amount':
                                        //if (value > record.yjye.value) { //这里写具体的业务判断条件
                                        // "201102BCLF-0011": "修改失败，输入的金额有误",
                                        if (parseFloat(value) > parseFloat(record.predict_rest_amount.value)) {
                                            toast({ content: multiLang && multiLang.get('201102BCLF-0011'), color: 'danger' });
                                            this.isError = true;
                                        } else {
                                            this.isError = false;
                                            let scale = record.predict_rest_amount.value.split('.')[1].length;
                                            let total = 0;
                                            //计算表头核销金额
                                            let selectrow = this.props.transferTable.getTransferTableSelectedValue();
                                            selectrow && selectrow.head.length && selectrow.head[0].body.accrued_detail.rows.forEach((row) => {
                                                total = parseFloat(total) + parseFloat(row.values.verify_amount.value);
                                            });
                                            this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { value: total, scale } }, record.parentRowId || record.headKey);
                                        }
                                        break;
                                }
                            }, //编辑后事件
                            onTransferBtnClick: (ids) => {//点击转单按钮钩子函数
                                // "201102BCLF-0011": "修改失败，输入的金额有误",
                                if (this.isError) {
                                    toast({ content: multiLang && multiLang.get('201102BCLF-0011'), color: 'danger' });
                                } else {

                                    window.pageFyytClick(ids);

                                }

                            },
                            onCheckedChange: (flag, record, index, bodys) => {
                                console.log('checked:', flag, record,index, bodys)
                                this.setTransferBtnDisabled(false);
                                let datas = [];
                                let total = 0;

                                if (record.parentRowId) {
                                    // record['hkybje'].value = 666;
                                    datas[0] = record;
                                } else if (bodys && bodys.length > 0) {
                                    datas = bodys;
                                }
                                if (flag == true) {
                                    datas.forEach((data) => {
                                        let scale = data.predict_rest_amount.value.split('.')[1].length;
										data['verify_amount'] = {
											scale,
											value: data["predict_rest_amount"].value
                                        };
                                        //计算表头核销金额
                                        total = parseFloat(data.verify_amount.value);
                                        // let selectrow = this.props.transferTable.getTransferTableSelectedValue();
                                        // selectrow && selectrow.head.length && selectrow.head[0].body.accrued_detail.rows.forEach((row) => {
                                        //     total = parseFloat(total) + parseFloat(row.values.verify_amount.value);
                                        // });
                                        this.props.transferTable.setRowDataByIndex('head', data, data.rowIndex);
                                        this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { scale: scale, value: total } }, data.parentRowId || data.headKey);
                                    });
                                } else {
                                    datas.forEach((data) => {
                                        let scale = data.predict_rest_amount.value.split('.')[1].length;
                                        let selectrow = this.props.transferTable.getTransferTableSelectedValue();
                                        total = parseFloat(0).toFixed(scale);
                                        // selectrow && selectrow.head.length && selectrow.head[0].body.accrued_detail.rows.forEach((row) => {
                                        //     total = (parseFloat(total) + parseFloat(row.values.verify_amount.value));
                                        // });
                                        data['verify_amount'] = { value: 0, scale } //.value = (0).toFixed(scale);

                                        this.props.transferTable.setRowDataByIndex('head', data, data.rowIndex);
                                        this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { value: total, scale } }, data.parentRowId || data.headKey);
                                    });
                                }
                            },
                            onChangeViewClick: () => {//点击切换视图钩子函数
                                if (!this.props.meta.getMeta()[window.fyytAreaCode.bodysArea]) {
                                    initTemplate.call(this, this.props); //加载主子拉平模板
                                }
                                this.props.transferTable.changeViewType(this.headTableId);

                            }
                        }
                    )}
                </div>
            </div>

        )
    }
}

Fyyt = createPage({
    mutiLangCode: '2011'
})(Fyyt);

ReactDOM.render(<Fyyt />, document.querySelector('#app'));
